import { useAPIUtils } from "@/components/APIUtilsProvider";
import EmptyListPlaceholder from "@/components/EmptyListPlaceHolder";
import { moreModals } from "@/components/moreModals";
import PageLayout from "@/components/PageLayout";
import RenderIf from "@/components/RenderIf";
import When from "@/components/When";
import {
  Button,
  Center,
  Flex,
  Group,
  Pagination,
  Paper,
  Select,
  Table,
  Text,
  TextInput,
} from "@mantine/core";
import { DateTimePicker } from "@mantine/dates";
import { useForm } from "@mantine/form";
import { IconSearch } from "@tabler/icons-react";
import dayjs from "dayjs";
import { useImmer } from "use-immer";
import UserPill from "../../components/UserPill";
import StatusRenderer from "./StatusRenderer";

export default function ApplicationList({ title, targetRole }) {
  const {
    restGET,
    tanstackQuery,
    tanstackInvalidate,
    restPOST,
    restPUT,
    restDELETE,
  } = useAPIUtils();

  const decide = async (id, action, comment) => {
    await restPUT(
      `/api/admin/${targetRole}/applications/${id}?action=${action}&comment=${comment}`
    );
    tanstackInvalidate(`/api/admin/${targetRole}/applications`);
    tanstackInvalidate(`/api/admin/${targetRole}/applications/${id}`);
  };

  const [pagingCondition, setPagingCondition] = useImmer({
    targetStatus: "",
    keyword: "",
    start: dayjs().subtract(7, "days").toDate(),
    end: new Date(),
    pageIndex: 0,
    pageSize: 10,
  });

  const searchForm = useForm({
    mode: "uncontrolled",
    initialValues: {
      start: dayjs().subtract(7, "days").toDate(),
      end: new Date(),
      keyword: "",
      targetStatus: "",
    },
    validate: {},
  });

  const search = (values) => {
    tanstackInvalidate(`/api/admin/${targetRole}/applications`);
    setPagingCondition({
      ...values,
      pageSize: pagingCondition.pageSize,
      pageIndex: 0,
    });
  };

  const applicationQuery = tanstackQuery(
    `/api/admin/${targetRole}/applications`,
    {
      ...pagingCondition,
      targetStatus: pagingCondition.targetStatus || "",
      start: dayjs(pagingCondition.start).format("YYYY-MM-DDTHH:mm:ss"),
      end: dayjs(pagingCondition.end).format("YYYY-MM-DDTHH:mm:ss"),
      pageNo: pagingCondition.pageIndex,
      pageSize: pagingCondition.pageSize,
    }
  );

  const totalPages = applicationQuery.data?.totalPages;
  const rows = applicationQuery.data?.content.map((application, index) => (
    <Table.Tr key={index}>
      <Table.Td>
        <Text>{index + 1}</Text>
      </Table.Td>

      <Table.Td>
        <UserPill user={application.applicant} />
      </Table.Td>
      <Table.Td>
        {dayjs(application.createdAt).format("YYYY/MM/DD HH:mm")}
      </Table.Td>
      <Table.Td>
        <StatusRenderer status={application.status} />
      </Table.Td>
      <Table.Td>
        <Group>
          <RenderIf auth="QualificationApproval">
            <Button
              size="xs"
              onClick={() =>
                moreModals.openDefaultConfirmModal({
                  title: "确定要通过该申请吗？",
                  onConfirm: () => {
                    decide(application.id, "APPROVE");
                  },
                })
              }
              disabled={application.status !== "PENDING"}
            >
              同意
            </Button>
            <Button
              color="red.7"
              size="xs"
              onClick={() =>
                moreModals.openPromptModal({
                  title: "请填写审批意见(拒绝原因)",
                  onConfirm: (comment) => {
                    decide(application.id, "REJECT", comment);
                  },
                })
              }
              disabled={application.status !== "PENDING"}
            >
              拒绝
            </Button>
          </RenderIf>
          <Button
            variant="subtle"
            size="xs"
            onClick={() =>
              window.open(
                `/${targetRole}/applications/${application.id}`,
                "_blank"
              )
            }
          >
            详情
          </Button>
        </Group>
      </Table.Td>
    </Table.Tr>
  ));

  return (
    <PageLayout title={title}>
      <form onSubmit={searchForm.onSubmit(search)}>
        <Flex
          mih={50}
          mb={44}
          gap="md"
          justify="flex-end"
          align="flex-end"
          direction="row"
          wrap="wrap"
        >
          <DateTimePicker
            description="时间开始"
            {...searchForm.getInputProps("start")}
            valueFormat="YYYY/MM/DD HH:mm"
            w={200}
          />
          <DateTimePicker
            description="时间结束"
            {...searchForm.getInputProps("end")}
            valueFormat="YYYY/MM/DD HH:mm"
            w={200}
          />
          <TextInput
            clearable
            placeholder="申请人"
            label="申请人"
            {...searchForm.getInputProps("keyword")}
          />
          <Select
            clearable
            placeholder="默认全部"
            label="状态"
            {...searchForm.getInputProps("targetStatus")}
            data={[
              { label: "待审批", value: "PENDING" },
              { label: "已通过", value: "APPROVED" },
              { label: "已驳回", value: "REJECTED" },
            ]}
          />

          <Button type="submit" rightSection={<IconSearch size={14} />}>
            搜索
          </Button>
        </Flex>
      </form>

      <When condition={rows?.length > 0}>
        <Paper p={"md"}>
          <Table verticalSpacing={"sm"}>
            <Table.Thead>
              <Table.Tr>
                <Table.Th w={"3%"}></Table.Th>
                <Table.Th w={"50%"}>申请人</Table.Th>
                <Table.Th w={"10%"}>申请时间</Table.Th>
                <Table.Th w={"15%"}>状态</Table.Th>
                <Table.Th>操作</Table.Th>
              </Table.Tr>
            </Table.Thead>
            <Table.Tbody>{rows}</Table.Tbody>
          </Table>
        </Paper>
        <Center mt={40}>
          <Pagination
            total={totalPages}
            value={pagingCondition.pageIndex + 1}
            onChange={(e) => {
              setPagingCondition({ ...pagingCondition, pageIndex: e - 1 });
            }}
          />
        </Center>
      </When>
      <When condition={rows?.length == 0}>
        <EmptyListPlaceholder />
      </When>
    </PageLayout>
  );
}
